package com.tensquare.common.auth.interceptor;

import com.tensquare.common.auth.annotation.Authority;
import com.tensquare.common.auth.enums.AuthorityType;
import com.tensquare.common.util.JwtUtil;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author: WangYaWei
 * @description:
 * @create: 2019-08-27 09:13
 **/
public class AuthorityInterceptor extends HandlerInterceptorAdapter{

    @Qualifier("commonJwtUtil")
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = null;
        //获取执行方法上的注解
        if(handler instanceof  HandlerMethod){
            handlerMethod = (HandlerMethod) handler;
        }else{
            return true;
        }

        Method method = handlerMethod.getMethod();
        Authority authority = method.getAnnotation(Authority.class);
        if (authority == null || "".equals(authority.value().trim())) {
            // 如果注解为null, 说明不需要拦截, 直接放过
            return true;
        }

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");

        String authorization = request.getHeader("Authorization");
        if(authorization != null && authorization.startsWith("Bearer ")){
            String token = authorization.substring(7);
            Claims claims = null;
            try {
                claims = jwtUtil.parseJwt(token);
            } catch (ExpiredJwtException e){
                //登录超时
                PrintWriter out = response.getWriter();
                out.print("{\"flag\":false, \"code\":"+ 401 +", \"message\":\"未登录\"}");
                out.flush();
                return false;
            }


            if(AuthorityType.ADMIN.getValue().equals(authority.value())){
                if(AuthorityType.ADMIN.getValue().equals(claims.get("roles"))){
                    return true;
                }else{
                    //权限不足
                    PrintWriter out = response.getWriter();
                    out.print("{\"flag\":false, \"code\":"+ StatusCode.ACCESS_ERROR+", \"message\":\"权限不足\"}");
                    out.flush();
                    return false;
                }
            }else{
                if(claims == null){
                    //权限不足
                    // 脱离了Spring MVC的返回流程，重新编码
                    PrintWriter out = response.getWriter();
                    out.print("{\"flag\":false, \"code\":"+ StatusCode.ACCESS_ERROR+", \"message\":\"权限不足\"}");
                    out.flush();
                    return false;
                }
            }

        }else{
            //权限不足
            // 脱离了Spring MVC的返回流程，重新编码
            PrintWriter out = response.getWriter();
            out.print("{\"flag\":false, \"code\":"+ 401 +", \"message\":\"未登录\"}");
            out.flush();
            return false;
        }
        return true;
    }
}
